﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.Text.RegularExpressions;

using Wicresoft.Shell.Data;
using Wicresoft.Shell.Logic.Properties;
using Wicresoft.Shell.Core;

namespace Wicresoft.Shell.Logic
{

    public class DatabaseLogic
    {
        #region Fields

        private String m_ConnectionString;

        #endregion

        #region Constructor

        public DatabaseLogic()
        {
            m_ConnectionString = ConfigurationManager.ConnectionStrings["mobilegov_wcEntities"].ConnectionString;
        }

        public DatabaseLogic(String cnnStr)
        {
            m_ConnectionString = cnnStr;
        }

        #endregion

        #region Methods
        
        #region Select Data
        public IEnumerable<ApplicationTable> GetApplicationTableData()
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var applications = from t in database.application
                                   select new ApplicationTable
                                {
                                    APP_ID = t.APP_ID,
                                    APP_FATHER_ID = t.application2.APP_ID,
                                    APP_CODE = t.APP_CODE,
                                    APP_DESC = t.APP_DESC,
                                    APP_NAME = t.APP_NAME,
                                    IS_LEAF = t.IS_LEAF
                                };

                return applications.ToArray(); ;
            }
        }

        public IEnumerable<FunctionTable> GetFunctionTableData()
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var functions = from t in database.function
                                select new FunctionTable
                                {
                                    APP_ID = t.application.APP_ID,
                                    FUNCTION_NAME = t.FUNCTION_NAME,
                                    FUNCTION_ID = t.FUNCTION_ID,
                                    FUNCTION_CODE = t.FUNCTION_CODE,
                                    FUNCTION_DESC = t.FUNCTION_DESC
                                };

                return functions.ToArray();
            }
        }

        public IEnumerable<ApplicationProfTable> GetApplicationProfTableDataByAppID(int appid)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var applicationsProf = from t in database.application_prof
                                       where t.application.APP_ID == appid
                                       select new ApplicationProfTable
                                       {
                                           APP_PROF_ID = t.APP_PROF_ID,
                                           APP_PROF_NAME = t.APP_PROF_NAME,
                                           APP_PROF_VALUE = t.APP_PROF_VALUE,
                                           APP_PROF_TYPE = t.APP_PROF_TYPE
                                       };

                return applicationsProf.ToArray();
            }
        }

        public IEnumerable<FunctionProfTable> GetFunctionProfTableDataByFuncID(int funcid)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var functionProf = from t in database.function_prof
                                   where t.function.FUNCTION_ID == funcid
                                   select new FunctionProfTable
                                       {
                                           CLIENT_SYS_TYPE = t.CLIENT_SYS_TYPE,
                                           FUNC_PROF_ID = t.FUNC_PROF_ID,
                                           FUNC_PROF_NAME = t.FUNC_PROF_NAME,
                                           FUNC_PROF_VALUE = t.FUNC_PROF_VALUE,
                                           FUNCTION_ID = t.function.FUNCTION_ID,
                                           FUNC_PROF_TYPE = t.FUNC_PROF_TYPE
                                       };

                return functionProf.ToArray();
            }
        }

        public IEnumerable<VersionTable> GetVersions()
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var versions = (from t in database.version
                                select new VersionTable
                                {
                                    CLIENT_SYS_TYPE = t.CLIENT_SYS_TYPE,
                                }).Distinct();


                return versions.ToArray();
            }
        }

        #endregion

        #region exist judge

        public bool DataTemplateIsExists(int funcid)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var functionProf = from t in database.function_prof
                                   where t.function.FUNCTION_ID == funcid && t.FUNC_PROF_NAME == "DATA_TEMPLATE"
                                   select t;

                return (functionProf.Count() > 0);
            }
        }

        public bool FunctionExProfIsExists(FunctionProfTable fpt)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var functionProf = from t in database.function_prof
                                   where t.function.FUNCTION_ID == fpt.FUNCTION_ID && t.FUNC_PROF_NAME == fpt.FUNC_PROF_NAME
                                   select t;

                return (functionProf.Count() > 0);
            }
        }

        public bool ApplicationExProfIsExists(ApplicationProfTable apt)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var applicationProf = from t in database.application_prof
                                      where t.application.APP_ID == apt.APP_ID && t.APP_PROF_NAME == apt.APP_PROF_NAME
                                   select t;

                return (applicationProf.Count() > 0);
            }
        }
        #endregion


        #region Update Data

        public void UpdateFunctionExtensionProfTypeAndName(int FunctionProfId, string type, string name)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<function_prof> targets = database.function_prof.Where(function_prof
                    => (function_prof.FUNC_PROF_ID == FunctionProfId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).FUNC_PROF_TYPE = type;
                targets.ElementAt(0).FUNC_PROF_NAME = name;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }

        public void UpdateApplicationExtensionProfTypeAndName(int ApplicationProfId, string type, string name)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<application_prof> targets = database.application_prof.Where(application_prof
                    => (application_prof.APP_PROF_ID == ApplicationProfId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).APP_PROF_TYPE = type;
                targets.ElementAt(0).APP_PROF_NAME = name;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }

        public void UpdateAdapterType(int funcProfId, string Type)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<function_prof> targets = database.function_prof.Where(function_prof
                    => (function_prof.FUNC_PROF_ID == funcProfId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).CLIENT_SYS_TYPE = Type;
                database.SaveChanges();
                Logger.Output("更新成功");
            }

        }

        public void UpdateFunctionName(int funcId, string aName)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<function> targets = database.function.Where(function
                    => (function.FUNCTION_ID == funcId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).FUNCTION_NAME = aName;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }

        public void UpdateApplicationName(int appId, string aName)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<application> targets = database.application.Where(application
                    => (application.APP_ID == appId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).APP_NAME = aName;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }


        public void UpdateFunctionProfValue(int funcId, int funcProfId, string funcProfValue)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<function_prof> targets = database.function_prof.Where(functionProf
                    => (functionProf.function.FUNCTION_ID == funcId) && (functionProf.FUNC_PROF_ID == funcProfId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).FUNC_PROF_VALUE = funcProfValue;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }

        public void UpdateApplicationProfValue(int appId, int appProfId, string appProfValue)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                Logger.Output("正在更新数据库，请勿关闭程序");
                IEnumerable<application_prof> targets = database.application_prof.Where(applicationProf
                    => (applicationProf.application.APP_ID == appId) && (applicationProf.APP_PROF_ID == appProfId));
                if (targets.Count() != 1)
                {
                    throw new Exception("更新失败");
                }
                targets.ElementAt(0).APP_PROF_VALUE = appProfValue;
                database.SaveChanges();
                Logger.Output("更新成功");
            }
        }


        //Modify code for cut/copy functions;Review code: SunRui
        public string CopyApplicationNode(int appID, int newFatherID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                string insertResultName = "";
                insertResultName = CopySubApplicationNode(database, appID, newFatherID);
                return insertResultName;
            }
        }

        private string CopySubApplicationNode(mobilegov_wcEntities database, int appID, int newFatherID)
        {
            var appNode = database.application.First<application>(p => p.APP_ID == appID);
            Debug.Assert(appNode != null);
            var fartherNode = database.application.FirstOrDefault<application>(p => p.APP_ID == newFatherID);
            //获取原来应用下的子应用数量
            int count = database.application.Where(p => p.application2.APP_ID == appNode.APP_ID).Count();
            //获取原来应用下的子应用
            List<application> subApplicationList = database.application.Where(p => p.application2.APP_ID == appNode.APP_ID).ToList();

            //insert the appNode
            var insertResult = new application();
            insertResult.APP_CODE = appNode.APP_CODE;
            insertResult.APP_NAME = NameService(database,insertResult,newFatherID,appNode.APP_NAME,0);
            insertResult.APP_DESC = appNode.APP_DESC;
            insertResult.IS_LEAF = appNode.IS_LEAF;
            insertResult.application2 = fartherNode;
            database.AddToapplication(insertResult);
            database.SaveChanges();

            //get all the application_prof belogs to the appNode
            List<application_prof> application_profs = database.application_prof.Where(p => p.application.APP_ID == appNode.APP_ID).ToList();

            //insert the appliction_profs
            if (application_profs.Count > 0)
            {
                foreach (application_prof apf in application_profs)
                {
                    application_prof newapf = new application_prof();

                    newapf.application = insertResult;
                    newapf.APP_PROF_NAME = apf.APP_PROF_NAME;
                    newapf.APP_PROF_TYPE = apf.APP_PROF_TYPE;
                    newapf.APP_PROF_VALUE = apf.APP_PROF_VALUE;
                    database.AddToapplication_prof(newapf);
                }
                database.SaveChanges();
            }


            List<function> subfunctions = database.function.Where(p => p.application.APP_ID == appNode.APP_ID).ToList();
            if (subfunctions.Count > 0)
            {
                //insert the function and function_prof
                foreach (var fun in subfunctions)
                {
                    var f = new function();
                    f.FUNCTION_NAME = fun.FUNCTION_NAME;
                    f.FUNCTION_CODE = fun.FUNCTION_CODE;
                    f.FUNCTION_DESC = fun.FUNCTION_DESC;
                    f.application = insertResult;
                    database.AddTofunction(f);
                    database.SaveChanges();

                    //add function_prof
                    List<function_prof> subfunctionProfs = database.function_prof.Where(p => p.function.FUNCTION_ID == fun.FUNCTION_ID).ToList();
                    foreach (function_prof fp in subfunctionProfs)
                    {
                        function_prof newfp = new function_prof();
                        newfp.FUNC_PROF_NAME = fp.FUNC_PROF_NAME;
                        newfp.FUNC_PROF_TYPE = fp.FUNC_PROF_TYPE;
                        newfp.FUNC_PROF_VALUE = fp.FUNC_PROF_VALUE;
                        newfp.function = f;
                        newfp.CLIENT_SYS_TYPE = fp.CLIENT_SYS_TYPE;
                        database.AddTofunction_prof(newfp);
                    }
                    database.SaveChanges();
                }
            }

            //recursive adding the sub application
            if (count > 0)
            {
                foreach (var fartherApp in subApplicationList)
                {
                    CopySubApplicationNode(database, fartherApp.APP_ID, insertResult.APP_ID);
                }
            }

            //foreach (var fun in database.function.
            //    Where(p => p.application.APP_ID == appNode.APP_ID))
            //{
            //    var f = new function();
            //    f.FUNCTION_NAME = fun.FUNCTION_NAME;
            //    f.FUNCTION_CODE = fun.FUNCTION_CODE;
            //    f.FUNCTION_DESC = fun.FUNCTION_DESC;
            //    f.application = insertResult;
            //    database.AddTofunction(f);
            //}
            //database.SaveChanges();

            return insertResult.APP_NAME;
        }

        public string CutApplicationNode(int appID, int newFatherID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var row = database.application.First<application>(p => p.APP_ID == appID);
                row.application2 = database.application.FirstOrDefault<application>(p => p.APP_ID == newFatherID);
                row.APP_NAME = NameService(database, row, newFatherID, row.APP_NAME,0);
                database.SaveChanges();
                return row.APP_NAME;
            }
        }

        public string CopyFunctionNode(int funID, int newAppID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var funNode = database.function.First<function>(p => p.FUNCTION_ID == funID);
                var newAppNode = database.application.FirstOrDefault<application>(p => p.APP_ID == newAppID);
                var insertResult = new function();
                //insertResult.FUNCTION_NAME = String.Format(CultureInfo.CurrentCulture,
                //    Resources.DuplicatedNode, funNode.FUNCTION_NAME);
                insertResult.FUNCTION_NAME = NameService(database, insertResult, newAppID, funNode.FUNCTION_NAME,0);
                insertResult.FUNCTION_CODE = funNode.FUNCTION_CODE;
                insertResult.FUNCTION_DESC = funNode.FUNCTION_DESC;
                insertResult.application = newAppNode;

                database.AddTofunction(insertResult);
                database.SaveChanges();

                //add function_prof
                foreach (function_prof fp in database.function_prof.Where(p => p.function.FUNCTION_ID == funNode.FUNCTION_ID))
                {
                    function_prof newfp = new function_prof();
                    newfp.FUNC_PROF_NAME = fp.FUNC_PROF_NAME;
                    newfp.FUNC_PROF_TYPE = fp.FUNC_PROF_TYPE;
                    newfp.FUNC_PROF_VALUE = fp.FUNC_PROF_VALUE;
                    newfp.function = insertResult;
                    newfp.CLIENT_SYS_TYPE = fp.CLIENT_SYS_TYPE;
                    database.AddTofunction_prof(newfp);
                }
                database.SaveChanges();


                // return the Function ID of new node
                return insertResult.FUNCTION_NAME;
            }
        }

        public string CutFunctionNode(int funID, int newAppID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var row = database.function.First<function>(p => p.FUNCTION_ID == funID);
                row.application = database.application.FirstOrDefault<application>(p => p.APP_ID == newAppID);
                row.FUNCTION_NAME = NameService(database, row, newAppID, row.FUNCTION_NAME,0);
                database.SaveChanges();
                return row.FUNCTION_NAME;
            }
        }



        public bool UpdateApplicationProfTableData(IEnumerable<ApplicationProfTable> result)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    if (row.APP_PROF_ID > 0)
                    {
                        var updateResult = database.application_prof.First(p => p.APP_PROF_ID == row.APP_PROF_ID);
                        updateResult.APP_PROF_NAME = row.APP_PROF_NAME;
                        updateResult.APP_PROF_VALUE = row.APP_PROF_VALUE;
                    }
                    else{
                        var insertResult = new application_prof();
                        insertResult.application.APP_ID = (int)row.APP_ID;
                        insertResult.APP_PROF_NAME = row.APP_PROF_NAME;
                        insertResult.APP_PROF_VALUE = row.APP_PROF_VALUE;
                        database.AddToapplication_prof(insertResult);
                    }
                }

                database.SaveChanges();
            }

            return true;
        }




        public bool UpdateFunctionProfTableData(IEnumerable<FunctionProfTable> result)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                //database.DeleteObject(database.function_prof);

                foreach (var row in result)
                {
                    if (row.FUNC_PROF_ID > 0)
                    {
                        var updateResult = database.function_prof.First(p => p.FUNC_PROF_ID == row.FUNC_PROF_ID);
                        updateResult.FUNC_PROF_NAME = row.FUNC_PROF_NAME;
                        updateResult.FUNC_PROF_VALUE = row.FUNC_PROF_VALUE;
                    }
                    else
                    {
                        var insertResult = new function_prof();
                        insertResult.function.FUNCTION_ID = (int)row.FUNCTION_ID;
                        insertResult.FUNC_PROF_NAME = row.FUNC_PROF_NAME;
                        insertResult.FUNC_PROF_VALUE = row.FUNC_PROF_VALUE;
                        database.AddTofunction_prof(insertResult);
                    }
                }

                database.SaveChanges();
            }

            return true;
        }



        #endregion

        #region DeleteData

        //inner delete application
        private void DeleteApp(mobilegov_wcEntities db, int app_ID)
        {
            var delResult = db.application.FirstOrDefault<application>(p => p.APP_ID == app_ID);
            //delete app_prof first first
            delResult.application_prof.Load();
            List<application_prof> aplist = delResult.application_prof.ToList();
            foreach (application_prof ap in aplist)
            {
                db.DeleteObject(ap);
            }
            //delete functions first
            DeleteFunctionForApp(db, delResult);
            //delete sub app second
            List<application> subapps = db.application.Where(p => p.application2.APP_ID == delResult.APP_ID).ToList<application>();
            if (subapps.Count > 0)
            {
                foreach (application ap in subapps)
                    DeleteApp(db, ap.APP_ID);
            }
            db.DeleteObject(delResult);
        }

        //inner delete function of the application , but not save change
        private void DeleteFunctionForApp(mobilegov_wcEntities db, application _application)
        {
            _application.function.Load();
            if (_application.function.Count != 0)
            {
                List<function> dels = _application.function.ToList<function>();
                foreach (function r in dels)
                {
                    DeleteFunctionProfForFunction(db, r);
                    db.DeleteObject(r);
                }
            }
        }

        //inner delete function_prof of the function , but not save change
        private void DeleteFunctionProfForFunction(mobilegov_wcEntities db , function _function)
        {
            _function.function_prof.Load();
            if (_function.function_prof.Count != 0)
            {
                List<function_prof> dels = _function.function_prof.ToList<function_prof>();
                foreach (function_prof r in dels)
                    db.DeleteObject(r);
            }
        }

        //delete app by app id
        public void DeleteAppTableDataByID(int app_ID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                DeleteApp(database, app_ID);
                database.SaveChanges();
            }
        }

        //delete function by function id
        public void DeleteFunctionTableDataByID(int function_ID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var delResult = database.function.FirstOrDefault<function>(p => p.FUNCTION_ID == function_ID);
                DeleteFunctionProfForFunction(database,delResult);
                database.DeleteObject(delResult);
                database.SaveChanges();
            }
        }

        //delete function_prof by function id and function_Prof_ID
        public void DeleteFunctionProfByFunctionIDAndProfID(int function_ID, int function_Prof_ID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var delResult = from t in database.function_prof
                                where t.function.FUNCTION_ID == function_ID && t.FUNC_PROF_ID == function_Prof_ID
                                select t;
                foreach (var r in delResult)
                {
                    database.DeleteObject(r);
                }
                database.SaveChanges();
            }
        }

        //delete app_prof by app id and app_Prof_ID
        public void DeleteApplicationProfByAppIDAndProfID(int app_ID, int app_prof_ID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                var delResult = from t in database.application_prof
                                where t.application.APP_ID == app_ID && t.APP_PROF_ID == app_prof_ID
                                select t;
                foreach (var r in delResult)
                {
                    database.DeleteObject(r);
                }
                database.SaveChanges();
            }
        }

        #endregion

        #region InsertData

        //insert application
        public void InsertApplicationTableData(IEnumerable<ApplicationTable> result, ref int lastID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    var insertResult = new application();
                    insertResult.application2 = database.application.FirstOrDefault<application>(p => p.APP_ID == row.APP_FATHER_ID);
                    insertResult.APP_CODE = row.APP_CODE;
                    //insertResult.APP_NAME = row.APP_NAME;
                    insertResult.APP_NAME = NameService(database, insertResult, row.APP_FATHER_ID.Value, row.APP_NAME,0);
                    row.APP_NAME = insertResult.APP_NAME;
                    insertResult.APP_DESC = row.APP_DESC;
                    
                    database.AddToapplication(insertResult);
                    database.SaveChanges();
                    lastID = insertResult.APP_ID;
                }
            }
        }

        public void InsertApplicationProfTableData(IEnumerable<ApplicationProfTable> result , ref int lastID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    var insertResult = new application_prof();
                    insertResult.APP_PROF_NAME = row.APP_PROF_NAME;
                    insertResult.APP_PROF_VALUE = row.APP_PROF_VALUE;
                    insertResult.APP_PROF_TYPE = row.APP_PROF_TYPE;
                    insertResult.application = database.application.FirstOrDefault<application>(p => p.APP_ID == row.APP_ID);

                    database.AddToapplication_prof(insertResult);
                    database.SaveChanges();
                    lastID = insertResult.APP_PROF_ID;
                }
            }
        }

        //insert function
        public void InsertFunctionTableData(IEnumerable<FunctionTable> result , ref int lastID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    var insertResult = new function();
                    insertResult.application = database.application.FirstOrDefault<application>(p => p.APP_ID == row.APP_ID);
                    insertResult.FUNCTION_CODE = row.FUNCTION_CODE;
                    //insertResult.FUNCTION_NAME = row.FUNCTION_NAME;
                    insertResult.FUNCTION_NAME = NameService(database, insertResult, row.APP_ID.Value, row.FUNCTION_NAME,0);
                    row.FUNCTION_NAME = insertResult.FUNCTION_NAME;

                    insertResult.FUNCTION_DESC = row.FUNCTION_DESC;
                    
                    database.AddTofunction(insertResult);
                    database.SaveChanges();
                    lastID = insertResult.FUNCTION_ID;
                }
            }
        }

        //insert function prof and return lastid
        public void InsertFunctionProfTableData(IEnumerable<FunctionProfTable> result , ref int lastID)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    var insertResult = new function_prof();
                    insertResult.function = database.function.FirstOrDefault<function>(p => p.FUNCTION_ID == row.FUNCTION_ID);
                    insertResult.FUNC_PROF_NAME = row.FUNC_PROF_NAME;
                    insertResult.FUNC_PROF_VALUE = row.FUNC_PROF_VALUE;
                    insertResult.CLIENT_SYS_TYPE = row.CLIENT_SYS_TYPE;
                    insertResult.FUNC_PROF_TYPE = row.FUNC_PROF_TYPE;

                    database.AddTofunction_prof(insertResult);
                    database.SaveChanges();
                    lastID = insertResult.FUNC_PROF_ID;
                }
            }
        }

        //insert function prof not return
        public void InsertFunctionProfTableData(IEnumerable<FunctionProfTable> result)
        {
            using (mobilegov_wcEntities database = new mobilegov_wcEntities(m_ConnectionString))
            {
                foreach (var row in result)
                {
                    var insertResult = new function_prof();
                    insertResult.function = database.function.FirstOrDefault<function>(p => p.FUNCTION_ID == row.FUNCTION_ID);
                    insertResult.FUNC_PROF_NAME = row.FUNC_PROF_NAME;
                    insertResult.FUNC_PROF_VALUE = row.FUNC_PROF_VALUE;
                    insertResult.CLIENT_SYS_TYPE = row.CLIENT_SYS_TYPE;

                    database.AddTofunction_prof(insertResult);
                    database.SaveChanges();
                }
            }
        }


        #endregion

        #region service

        //provide a name for app or function in order to avoid rename
        //private string NameService(mobilegov_wcEntities db , object fatherType, int fatherID, string attempName)
        //{
        //    if (fatherType is application)
        //    {
        //        List<application> allchildren = new List<application>();
        //        allchildren = db.application.Where(p => p.application2.APP_ID == fatherID).ToList<application>();
        //        int count = 0;
        //        string pattern = attempName + @"( - Copy(\([0-9]+\))?)?";
        //        foreach (application sc in allchildren)
        //        {
        //            if (Regex.Match(sc.APP_NAME, pattern).Value == sc.APP_NAME)
        //                count++;
        //        }
        //        if (count > 0)
        //            return attempName + string.Format(" - Copy{0}", (count == 1) ? "" : string.Format("({0})", count));
        //        else
        //            return attempName;
        //    }
        //    else if (fatherType is function)
        //    {
        //        List<function> allchildren = new List<function>();
        //        allchildren = db.function.Where(p => p.application.APP_ID == fatherID).ToList<function>();
        //        int count = 0;
        //        string pattern = attempName + @"( - Copy(\([0-9]+\))?)?";
        //        foreach (function sc in allchildren)
        //        {
        //            if (Regex.Match(sc.FUNCTION_NAME, pattern).Value == sc.FUNCTION_NAME)
        //                count++;
        //        }
        //        if (count > 0)
        //            return attempName + string.Format(" - Copy{0}", (count == 1) ? "" : string.Format("({0})", count));
        //        else
        //            return attempName;
        //    }
        //    else
        //        return attempName;
        //}

        private string NameService(mobilegov_wcEntities db, object fatherType, int fatherID, string attempName,int extension)
        {
            int i = 0;
            if (fatherType is application)
            {
                List<application> allchildren = new List<application>();
                allchildren = db.application.Where(p => p.application2.APP_ID == fatherID).ToList<application>();
                while (true)
                {
                    if (i == 0)
                    {
                        if (allchildren.Where(p => p.APP_NAME == attempName).Count() > 0)
                        {
                            i += 2;
                        }
                        else
                        {
                            return attempName;
                        }
                    }
                    else
                    {
                        if (allchildren.Where(p => p.APP_NAME == attempName + string.Format(" ({0})", i)).Count() > 0)
                        {
                            i++;
                        }
                        else
                        {
                            return attempName + string.Format(" ({0})", i);
                        }
                    }
                }
            }
            else if (fatherType is function)
            {
                List<function> allchildren = new List<function>();
                allchildren = db.function.Where(p => p.application.APP_ID == fatherID).ToList<function>();
                while (true)
                {
                    if (i == 0)
                    {
                        if (allchildren.Where(p => p.FUNCTION_NAME == attempName).Count() > 0)
                        {
                            i += 2;
                        }
                        else
                        {
                            return attempName;
                        }
                    }
                    else
                    {
                        if (allchildren.Where(p => p.FUNCTION_NAME == attempName + string.Format(" ({0})", i)).Count() > 0)
                        {
                            i++;
                        }
                        else
                        {
                            return attempName + string.Format(" ({0})", i);
                        }
                    }
                }
            }
            else
                return attempName;
        }

        //private string TemplateNameService(int function_prof_id)
        //{
        //    using (mobilegov_wcEntities database = new mobilegov_wcEntities())
        //    {
        //        function f = database.function_prof.First<function_prof>(p => p.FUNC_PROF_ID == function_prof_id).function;
        //        application a = database.application.FirstOrDefault<application>(p=>p.APP_ID == f.application.APP_ID);
        //    }
        //}

        //private 

        #endregion


        #endregion

        #region Static Methods

        public static String BuildDataEntityCnnStr(String dataSrc, String dbStr, String userId, String pwdStr)
        {
            Debug.Assert(!String.IsNullOrEmpty(dataSrc), "dataSrc must be provided.");
            Debug.Assert(!String.IsNullOrEmpty(dbStr), "dbStr must be provided.");
            Debug.Assert(!String.IsNullOrEmpty(userId), "userId must be provided.");
            Debug.Assert(!String.IsNullOrEmpty(pwdStr), "pwdStr must be provided.");

            String cnnStrFormat = "metadata=res://*/Mobile.csdl|res://*/Mobile.ssdl|res://*/Mobile.msl;provider=MySql.Data.MySqlClient;provider connection string=\"server={0};User Id={2};database={1};password={3};Persist Security Info=True;Character Set=gb2312;Connect Timeout =5000\"";

            return String.Format(cnnStrFormat, dataSrc, dbStr, userId, pwdStr);
        }

        #endregion

        #region Properties

        public String ConnectionString
        {
            get { return m_ConnectionString; }
        }

        #endregion
    }

    public class FunctionProfTable
    {
        public string FUNC_PROF_NAME { get; set; }
        public string FUNC_PROF_VALUE { get; set; }
        public int FUNCTION_ID { get; set; }
        public int FUNC_PROF_ID { get; set; }
        public string CLIENT_SYS_TYPE { get; set; }
        public string FUNC_PROF_TYPE { get; set; }
    }

    public class ApplicationProfTable
    {
        public int? APP_ID { get; set; }
        public int APP_PROF_ID { get; set; }
        public string APP_PROF_NAME { get; set; }
        public string APP_PROF_VALUE { get; set; }
        public string APP_PROF_TYPE { get; set; }
    }

    public class ApplicationTable
    {
        public int APP_ID { get; set; }
        public int? APP_FATHER_ID { get; set; }
        public string APP_NAME { get; set; }
        public string APP_DESC { get; set; }
        public string APP_CODE { get; set; }
        public int? IS_LEAF { get; set; }
    }

    public class FunctionTable
    {
        public string FUNCTION_NAME { get; set; }
        public int? APP_ID { get; set; }
        public int FUNCTION_ID { get; set; }
        public string FUNCTION_CODE { get; set; }
        public string FUNCTION_DESC { get; set; }
    }

    public class VersionTable
    {
        public string CLIENT_SYS_TYPE{get;set;}
    }
}
